package org.xxpay.pay.channel.qianhuitong;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import org.springframework.stereotype.Service;
import org.xxpay.common.http.HttpRequestTemplate;
import org.xxpay.common.util.sign.SignUtils;
import org.xxpay.common.util.str.StringUtils;
import org.xxpay.core.common.constant.PayConstant;
import org.xxpay.core.common.util.AmountUtil;
import org.xxpay.core.entity.PayOrder;
import org.xxpay.pay.channel.BasePayment;

import java.util.Map;

@Service
public class QianhuitongPaymentService extends BasePayment {
    private final static String logPrefix = "【黔汇通】";
    @Override
    public String getChannelName() {
        return QianhuitongConfig.CHANNEL_NAME;
    }

    /**
     * 支付下单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject pay(PayOrder payOrder) {
        return doOrderReq(payOrder);
    }

    /**
     * 查询订单
     * @param payOrder
     * @return
     */
    @Override
    public JSONObject query(PayOrder payOrder) {
        QianhuitongConfig config = new QianhuitongConfig(getPayParam(payOrder));
        String payOrderId = payOrder.getPayOrderId();
        _log.info("{}开始查询通道订单,payOrderId={}", logPrefix, payOrderId);
        Map<String, Object> params = Maps.newHashMap();
        params.put("fxid", config.getAppId());
        params.put("fxddh", payOrderId);
        params.put("fxaction","orderquery");
        params.put("fxsign", getSignQuery(params, config.getPrivateKey()));
        _log.info("{}订单查询请求数据:{}", getChannelName(), JSON.toJSONString(params));
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl(), params, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals(origin.getString("fxstatus"), "1")) {
            retObj.put("status",2);
            retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
            retObj.put("channelOrderNo", origin.getString("fxddh"));
            retObj.put("channelObj", origin);
            return retObj;
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.getString("error"));
        return retObj;
    }

    //下单具体实现
    private JSONObject doOrderReq(PayOrder payOrder){
        QianhuitongConfig config = new QianhuitongConfig(getPayParam(payOrder));
        Map<String,Object> parameters = Maps.newHashMap();
        //设置参数
        setParams(payOrder,config,parameters);
        _log.info("{}请求数据:{}", getChannelName(), JSON.toJSONString(parameters));
        //将订单改为支付中
        rpcCommonService.rpcPayOrderService.updateStatus4Ing(payOrder.getPayOrderId(), null);
        HttpRequestTemplate requestTemplate = new HttpRequestTemplate(null);
        JSONObject origin = requestTemplate.postForObject(config.getRequestUrl()+QianhuitongConfig.pay_url_fixx, parameters, JSONObject.class);
        _log.info("{}响应数据:{}", getChannelName(), JSON.toJSONString(origin));
        // 响应对象
        JSONObject retObj = new JSONObject();
        if(StringUtils.equals("1",origin.getString("status"))){
            return buildPayResultOfForm(retObj, payOrder,"<script type=\"text/javascript\">\n" +
                    "　　window.location.href=\""+ origin.getString("payurl")+"\";\n" +
                    "　　</script>" ,origin.getString("sdk_url"));
        }
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_FAIL);
        retObj.put(PayConstant.RESULT_PARAM_ERRDES, origin.toJSONString());
        return retObj;
    }

    //设置请求参数
    private void setParams(PayOrder payOrder,QianhuitongConfig config,Map<String,Object> params){
        params.put("fxid", config.getAppId());
        params.put("fxddh", payOrder.getPayOrderId());
        params.put("fxdesc", payOrder.getPayOrderId());
        params.put("fxfee", AmountUtil.convertCent2Dollar(String.valueOf(payOrder.getAmount())));
        //params.put("fxattch", payOrder.getPayOrderId());
        params.put("fxnotifyurl", payConfig.getNotifyUrl(getChannelName()));
        params.put("fxbackurl", payOrder.getReturnUrl());
        params.put("fxpay", config.getPayMode());
        params.put("fxip", payOrder.getClientIp());
        params.put("fxuserid", payOrder.getPayOrderId());
        params.put("fxsign", getSign(params,config.getPrivateKey()));
    }

    //获取sign
    private String getSign(Map<String,Object> params,String key){
        String signTxt = params.get("fxid").toString()+params.get("fxddh").toString()+params.get("fxfee").toString()+
                params.get("fxnotifyurl").toString()+key;
        _log.info("{}待签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, "", SignUtils.CHARSET_UTF8);
        return sign;
    }
    private String getSignQuery(Map<String,Object> params,String key){
        String signTxt = params.get("fxid").toString()+params.get("fxddh").toString()+params.get("fxaction").toString()+key;
        _log.info("{}待签名字符串：{}", logPrefix, signTxt);
        String sign = SignUtils.MD5.createSign(signTxt, "", SignUtils.CHARSET_UTF8);
        return sign;
    }

    protected JSONObject buildPayResultOfForm(JSONObject retObj, PayOrder payOrder, String payForm,String sdk_url) {
        // 设置支付订单ID
        retObj.put("payOrderId", payOrder.getPayOrderId());
        // 具体付款内容
        JSONObject payInfo = new JSONObject();
        payInfo.put("payUrl",payForm);
        retObj.put("sdk_url", sdk_url);
        payInfo.put("payMethod",PayConstant.PAY_METHOD_FORM_JUMP);
        retObj.put("payParams", payInfo);
        retObj.put(PayConstant.RETURN_PARAM_RETCODE, PayConstant.RETURN_VALUE_SUCCESS);
        return retObj;
    }
}